import axios, { AxiosResponse } from "axios";
import { DiscussModel } from "../models/Discuss";

class DiscussApis {
    sendDiscuss(discuss: DiscussModel): Promise<boolean> {
        let promise: Promise<boolean> = new Promise((resolve, reject) => {
            axios.post('/api/discuss/discuss', discuss)
                .then((reslut: AxiosResponse) => {
                    const code: number = reslut.data.code;
                    if (code == 200) {
                        resolve(true);
                    } else {
                        reject(false);
                    }
                })
                .catch((error) => {
                    reject(error);
                })
        });
        return promise;
    }

    queryDiscuss(id: number): Promise<Array<DiscussModel>> {
        let promise: Promise<Array<DiscussModel>> = new Promise((resolve, reject) => {
            let obj: object = {
                id: id
            };
            axios.get('/api/discuss/discuss', { params: obj })
                .then((reslut: AxiosResponse) => {
                    const code: number = reslut.data.code;
                    if (code == 200) {
                        let discussList: Array<DiscussModel> = reslut.data.data;
                        resolve(discussList);
                    } else {
                        reject(reslut.data);
                    }
                })
                .catch((error) => {
                    reject(error);
                })
        });
        return promise;
    }

    // 新增：删除评论，需传评论id与用户id
    deleteDiscuss(id: number, userId: string): Promise<boolean> {
        const promise: Promise<boolean> = new Promise((resolve, reject) => {
            const params = { id, user: userId };
            axios.delete('/api/discuss/discuss', { params })
                .then((result: AxiosResponse) => {
                    const code: number = result.data.code;
                    if (code === 200) {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                })
                .catch((error) => reject(error));
        });
        return promise;
    }
}

export const discussApis: DiscussApis = new DiscussApis();